'use client';

import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { message } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import styles from './AuthGuard.module.scss';

// 用户信息接口
export interface User {
  id: string;
  username: string;
  email: string;
  displayName: string;
  role: string;
  avatar?: string;
  status: string;
  emailVerified: boolean;
  loginCount: number;
  lastLogin?: string;
  createdAt: string;
}

// 认证上下文接口
interface AuthContextType {
  user: User | null;
  loading: boolean;
  isAuthenticated: boolean;
  login: (emailOrUsername: string, password: string) => Promise<boolean>;
  register: (userData: {
    username: string;
    email: string;
    password: string;
    displayName?: string;
  }) => Promise<boolean>;
  logout: () => Promise<void>;
  refreshAuth: () => Promise<void>;
  updateUser: (userData: Partial<User>) => void;
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者组件
export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // 检查认证状态
  const checkAuth = async () => {
    try {
      const response = await fetch('/api/auth/me', {
        credentials: 'include',
      });

      if (response.ok) {
        const data = await response.json();
        setUser(data.user);
        setIsAuthenticated(true);
      } else {
        setUser(null);
        setIsAuthenticated(false);
      }
    } catch (error) {
      console.error('检查认证状态失败:', error);
      setUser(null);
      setIsAuthenticated(false);
    } finally {
      setLoading(false);
    }
  };

  // 登录
  const login = async (emailOrUsername: string, password: string): Promise<boolean> => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ emailOrUsername, password }),
      });

      const data = await response.json();

      if (response.ok) {
        setUser(data.user);
        setIsAuthenticated(true);
        message.success(data.message || '登录成功');
        return true;
      } else {
        message.error(data.error || '登录失败');
        return false;
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error('网络错误，请稍后重试');
      return false;
    }
  };

  // 注册
  const register = async (userData: {
    username: string;
    email: string;
    password: string;
    displayName?: string;
  }): Promise<boolean> => {
    try {
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(userData),
      });

      const data = await response.json();

      if (response.ok) {
        setUser(data.user);
        setIsAuthenticated(true);
        message.success(data.message || '注册成功');
        return true;
      } else {
        message.error(data.error || '注册失败');
        return false;
      }
    } catch (error) {
      console.error('注册错误:', error);
      message.error('网络错误，请稍后重试');
      return false;
    }
  };

  // 登出
  const logout = async (): Promise<void> => {
    try {
      const response = await fetch('/api/auth/logout', {
        method: 'POST',
        credentials: 'include',
      });

      const data = await response.json();
      
      if (response.ok) {
        message.success(data.message || '登出成功');
      }
    } catch (error) {
      console.error('登出错误:', error);
    } finally {
      // 无论请求是否成功，都清除本地状态
      setUser(null);
      setIsAuthenticated(false);
    }
  };

  // 刷新认证状态
  const refreshAuth = async (): Promise<void> => {
    setLoading(true);
    await checkAuth();
  };

  // 更新用户信息
  const updateUser = (userData: Partial<User>): void => {
    if (user) {
      setUser({ ...user, ...userData });
    }
  };

  // 自动刷新token
  useEffect(() => {
    const refreshToken = async () => {
      try {
        const response = await fetch('/api/auth/refresh', {
          method: 'POST',
          credentials: 'include',
        });

        if (!response.ok) {
          // 如果刷新失败，清除认证状态
          setUser(null);
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error('Token刷新失败:', error);
        setUser(null);
        setIsAuthenticated(false);
      }
    };

    // 每30分钟尝试刷新token
    const interval = setInterval(refreshToken, 30 * 60 * 1000);

    return () => clearInterval(interval);
  }, []);

  // 组件挂载时检查认证状态
  useEffect(() => {
    checkAuth();
  }, []);

  // 监听页面可见性变化，重新检查认证状态
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible' && isAuthenticated) {
        checkAuth();
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
  }, [isAuthenticated]);

  const value: AuthContextType = {
    user,
    loading,
    isAuthenticated,
    login,
    register,
    logout,
    refreshAuth,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

// 使用认证上下文的Hook
export function useAuth(): AuthContextType {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}

// 认证守卫组件
export function AuthGuard({ 
  children, 
  fallback, 
  requireAdmin = false 
}: { 
  children: ReactNode; 
  fallback?: ReactNode; 
  requireAdmin?: boolean;
}) {
  const { isAuthenticated, user, loading } = useAuth();

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return fallback || (
      <div className={styles.authGuardContainer}>
        <div className={styles.authGuardCard}>
          <div className={styles.icon}>
            <LockOutlined />
          </div>
          <h2 className={styles.title}>需要登录</h2>
          <p className={styles.subtitle}>请先登录以访问此页面</p>
          <a 
            href="/login" 
            className={styles.loginButton}
          >
            <UserOutlined />
            前往登录
          </a>
        </div>
      </div>
    );
  }

  if (requireAdmin && user?.role !== 'admin') {
    return (
      <div className={styles.authGuardContainer}>
        <div className={styles.permissionDeniedCard}>
          <div className={styles.icon}>
            <UserOutlined />
          </div>
          <h2 className={styles.title}>权限不足</h2>
          <p className={styles.subtitle}>您没有访问此页面的权限</p>
          <a 
            href="/" 
            className={styles.loginButton}
          >
            返回首页
          </a>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}

export default AuthContext;